package io.wdb.config;

import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
public class AmqpConfig {

    public static final String TOPIC_EXCHANGE = "amq.topic";
    public static final String ALARM_QUEUE_NAME = ".ibms.alarm";
    public static final String MESSAGE_QUEUE_NAME = ".ibms.message";

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        return template;
    }

    @Bean(name="aRabbitListenerContainerFactory")
    public SimpleRabbitListenerContainerFactory arabbitListenerContainerFactory(
            ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setPrefetchCount(5);
        //factory.setConcurrentConsumers(5);
        //factory.setMessageConverter(new Jackson2JsonMessageConverter());

        return  factory;
    }

    @Bean
    Queue queueForAlarm() {
        return QueueBuilder.durable(ALARM_QUEUE_NAME).build();
    }

    @Bean
    Binding bindingForAlarm(Queue queueForAlarm) {
        return BindingBuilder.bind(queueForAlarm).to(new TopicExchange(TOPIC_EXCHANGE)).with(queueForAlarm.getName());
    }
}
